import 'package:flutter/material.dart';
import 'package:bloctest/pages/home_page/home_page_present.dart';
import 'package:bloctest/utils/RefreshWidget.dart';
import 'package:flutter_swiper_view/flutter_swiper_view.dart';
import 'package:provider/provider.dart';

import '../../model/home_artcle_model.dart';
import '../../utils/RouteUtils.dart';
import '../../utils/Routes.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key});

  // This widget is the home page of your application. It is stateful, meaning
  // that it has a State object (defined below) that contains fields that affect
  // how it looks.

  // This class is the configuration for the state. It holds the values (in this
  // case the title) provided by the parent (in this case the App widget) and
  // used by the build method of the State. Fields in a Widget subclass are
  // always marked "final".

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  HomePresent present = HomePresent();
  late RefreshController _controller;


  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _controller=  RefreshController();
    present.getBanner();
    present.getNotice(true);
  }

  @override
  Widget build(BuildContext context) {
    // This method is rerun every time setState is called, for instance as done
    // by the _incrementCounter method above.
    //
    // The Flutter framework has been optimized to make rerunning build methods
    // fast, so that you can just rebuild anything that needs updating rather
    // than having to individually change instances of widgets.
    return Scaffold(
      // appBar: AppBar(
      //   title: Text(widget.title),
      // ),
      body: bodyContent(present),
    );
  }


  Widget bodyContent(HomePresent present) {
    return ChangeNotifierProvider<HomePresent>(
        create: (context) {
          return present;
        },
        child: SafeArea(
            child: RefreshWidget(
          controller: _controller,
          onRefresh: () => {
            present
                .getNotice(true)
                .then((value) => _controller.refreshCompleted())
          },
          onLoading: () {
            present
                .getNotice(false)
                .then((value) => _controller.loadComplete());
          },
          child: SingleChildScrollView(
            child: Container(
              child: Column(
                children: [
                  _banner(),
                  _contentList(),
                ],
              ),
            ),
          ),
        )));
  }

  Widget _banner() {
    return Consumer<HomePresent>(builder: (context, vm, child) {
      return Container(
        width: double.infinity,
        height: 150.h,
        child: Swiper(
          itemCount: vm.bannerList?.length ?? 0,
          itemBuilder: (context, index) {
            return Image.network(
              vm.bannerList?[index].imagePath ?? '',
              fit: BoxFit.fill,
            );
          },
          pagination: const SwiperPagination(), //下标自动翻页
          control: const SwiperControl(), //左右切换翻页
        ),
      );
    });
  }

  Widget _contentList() {
    return Consumer<HomePresent>(builder: (context, vm, child) {
      return ListView.builder(
        physics: NeverScrollableScrollPhysics(),
        shrinkWrap: true,
        itemBuilder: (BuildContext context, int index) {
          return itemWidget(context, vm.homeList![index]);
        },
        itemCount: vm.homeList?.length ?? 0,
      );
    });
  }

  Widget itemWidget(BuildContext context, ArticleItems items) {
    return InkWell(
        onTap: () {
          RouteUtils.pushForName(context, RouterPath.Pic,
              arguments: {"title": "web"});
        },
        child: Container(
            decoration: BoxDecoration(
                border: Border.all(width: 1.w, color: Colors.black12),
                borderRadius: BorderRadius.all(Radius.circular(10.r))),
            padding: EdgeInsets.all(10),
            margin:
                EdgeInsets.only(left: 10.w, right: 10.w, top: 5.h, bottom: 5.h),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    // ClipRRect(
                    //   child: Image.asset("assets/images/icon_head.jpeg",
                    //       width: 30, height: 30,fit: BoxFit.fill,),
                    //   borderRadius: BorderRadius.all(Radius.circular(15)),
                    //
                    // ),
                    CircleAvatar(
                      radius: 15.r,
                      backgroundImage:
                          AssetImage('assets/images/icon_head.jpeg'),
                      child: Container(
                        decoration: BoxDecoration(
                            borderRadius:
                                BorderRadius.all(Radius.circular(15.r)),
                            border:
                                Border.all(color: Colors.white, width: 2.w)),
                      ),
                    ),
                    SizedBox(
                      width: 10.w,
                    ),
                    Text(items.author ?? ''),
                    Expanded(child: SizedBox()),
                    Text(items.niceShareDate ?? ''),
                    SizedBox(width: 10.w),
                    Text(
                      '置顶',
                      style: TextStyle(color: Colors.blue, fontSize: 12.sp),
                    ),
                  ],
                ),
                Padding(
                  padding: EdgeInsets.only(top: 5.h, bottom: 5.h),
                  child: Text(
                    items.title ?? '',
                    style: TextStyle(fontWeight: FontWeight.bold),
                  ),
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text(items.chapterName ?? "",
                        style: TextStyle(color: Colors.greenAccent)),
                    Image.asset(
                      "assets/images/icon_collect.png",
                      width: 20.w,
                      height: 20.h,
                    )
                  ],
                )
              ],
            )));
  }

  @override
  void dispose() {
    // TODO: implement dispose
    _controller.dispose();
    super.dispose();
  }
}
